import { Provide, Inject } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository } from "typeorm";
import { MenuEntity } from "@/entity/system/menu.entity";
import { UserEntity } from "@entity/system/user.entity";
import { handleMenuTree } from '@utils/tree';
import { resBuild } from "@utils/resBuild";

/**
 * getRouters()：获取基本的菜单路由表，按身份
 */

@Provide()
export class GetRouterService {

  @Inject()
  ctx: Context;

  @InjectEntityModel(MenuEntity)
  protected menuEntity: Repository<MenuEntity>;

  @InjectEntityModel(UserEntity)
  protected userEntity: Repository<UserEntity>;

  // 查询菜单路由
  async getRouters() {
    // 如果user_id为1，则为超管，获取所有菜单；否则根据user_id获取菜单
    const userId = this.ctx.session.userInfo.userId;
    // 如果是超级管理员，则获取所有菜单
    if(userId === 1) {

      // 所有菜单，取其中一部分字段
      const allMenus = await this.menuEntity.find({
        select: ['menuId', 'menuName', 'parentId', 'path', 'component','menuType', 'visible', 'status', 'icon', 'isCache', 'isFrame'],
        order: {
          orderNum: 'ASC',
          createTime: 'DESC'
        }
      });
      // 只保留菜单和目录
      const filterMenus = allMenus.filter(item => item.menuType === 'M' || item.menuType === 'C');
      return resBuild.data(handleMenuTree(filterMenus) || [])
    } else {
      // 查询该用户的菜单
      const userResult = await this.userEntity.findOne({
        where: {
          userId
        },
        relations: ['roles', 'roles.menus'], // 这里需要现在实体中定义关联关系
      });
      // 处理数据格式
      const menuList = []
      userResult.roles.forEach(item => {
        menuList.push(...item.menus)
      })
      // 只保留菜单和目录
      const filterMenus = menuList.filter(item => item.menuType === 'M' || item.menuType === 'C');
      return resBuild.data(handleMenuTree(filterMenus) || [])
    }
  }
}
